"use strict"
/// <reference path="../../index.d.ts" />
const Controller = require("egg").Controller
const {sendStat, md5} = require("../extend/helper")
//管理员
class ApiApplicatController extends Controller {
	constructor(ctx) {
		super(ctx)
		this.constant = this.config.constant
		this.serverConfig = this.config.serverConfig
	}
	async login() {
		const {ctx, constant} = this
		const User = ctx.model.AdminUser
		const req = ctx.request
		const account = req.body.account
		const password = req.body.password

		ctx.validate({account: "email", password: "string"}, req.body)
		const user = await User.findOne({
			where: {account},
		})
		if (!user) {
			ctx.body = sendStat(constant.ERROR_USER_ACCOUNT_NOEXIST)
			return
		}
		let md5pass = md5(user.password + ((Date.now() / 1000 / 60) | 0).toString(36))
		if (password !== md5pass) { // todo
			ctx.body = sendStat(constant.ERROR_USER_PASSWORD_NOMATCH)
			return
		}
		User.update({last_login: Date.now()}, {where: {id: user.id}})
		ctx.session.adminUser = {
			id: user.id,
			account: user.account,
		}
		ctx.body = sendStat(constant.NORMAL, {user: {account}})
	}
	async userInfo() {
		if (this.ctx.session.adminUser)
			this.ctx.body = sendStat(this.constant.NORMAL, this.ctx.session.adminUser)
		else
			this.ctx.body = sendStat(this.constant.ERROR_USER_LOGIN_FAIL, {})
	}

	async logout() {
		this.ctx.session
	}
}

module.exports = ApiApplicatController
